//
//  Scene01.swift
//  FirstGame
//
//  Created by Apple on 2017/12/21.
//  Copyright © 2017年 Apple. All rights reserved.
//

import SpriteKit

class Scene01: GameScene {
    
    var hat: SKSpriteNode!
    var snow: SKEmitterNode!
    
    var touchPoint: CGPoint?
    var physicsBodyFrame: CGRect!
    
    override func sceneDidLoad() {
        super.sceneDidLoad()
        
        btnPrevious?.isHidden = true
        
        hat = childNode(withName: "hat") as! SKSpriteNode
        snow = childNode(withName: "snow") as! SKEmitterNode
        
        physicsBodyFrame = .zero
        physicsBodyFrame.origin.x = -size.width * 0.5
        physicsBodyFrame.origin.y = -size.height * 0.5 + 85
        physicsBodyFrame.size = size
        physicsBody = SKPhysicsBody(edgeLoopFrom: physicsBodyFrame)
    }
    
    override func touchDown(at point: CGPoint) {
        if hat.contains(point) {
            // 保存触摸的位置
            touchPoint = point
            
            hat.physicsBody?.velocity = .zero   // 速度0
            hat.physicsBody?.angularVelocity = 0    // 角速度0
            hat.physicsBody?.affectedByGravity = false  // 不受重力影响
        }
    }
    
    override func touchMoved(to point: CGPoint) {
        // 移动超出边界了
        if point.y < physicsBodyFrame.minY { return }
        // 更新touchPoint
        if touchPoint != nil { touchPoint = point }
    }
    
    override func touchUp(at point: CGPoint) {
        if touchPoint != nil {
            hat.physicsBody?.affectedByGravity = true
            
            if let hatPosition = childNode(withName: "hatPosition"), hatPosition.contains(point) {
                
                hat.physicsBody?.affectedByGravity = false  // 不受重力影响
                let move = SKAction.move(to: hatPosition.position, duration: 0.25)
                let playSound = SKAction.playSoundFileNamed("thompsonman_pop.mp3", waitForCompletion: false)
                hat.run(SKAction.sequence([move, playSound]))
                
                // 切换下雪状态
                snow.particleTexture = SKTexture(imageNamed: "icecream")
            } else {
                snow.particleTexture = SKTexture(imageNamed: "spark")
            }
        }
        touchPoint = nil
    }
    
    override func update(_ currentTime: TimeInterval) {
        if let touchPoint = touchPoint {
            hat.position = touchPoint
        }
    }
    override func getPreviousScene() -> SKScene? {
        return SKScene(fileNamed: "HomeScene")
    }
    override func getNextScene() -> SKScene? {
        return SKScene(fileNamed: "Scene02")
    }
}
